package com.ifcar.app.activity;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;

import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.weibo.WeiboLogin;
import com.ifcar.app.activity.R;

public class AccountSettingActivity extends BaseActivity {
	
	private Button account_signout;
	private Button account_signin;
	private Button account_signup;
	private TextView account_text;
	private SharedPreferences set_prefs;
	private String account;
	private TextView title;
	private ListView account_list;
	private SimpleAdapter adapter;
	private ImageView netease_img;
	private TextView foottextview;
	private ArrayList<HashMap<String, Object>> accountListData = new ArrayList<HashMap<String, Object>>();;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.account_layout);
		set_prefs = PreferenceManager.getDefaultSharedPreferences(this);
		account_text = (TextView) findViewById(R.id.account_text);
		account_signout = (Button) findViewById(R.id.account_signout);
		account_signin = (Button) findViewById(R.id.account_signin);
		account_signup = (Button)findViewById(R.id.account_signup);
		title = (TextView) findViewById(R.id.top_main_text);
		title.setText(this.getResources().getString(R.string.personal_account));
		
		netease_img = (ImageView) findViewById(R.id.netease_img);
		
		
		account = set_prefs.getString("account", "");
		
		if(!"".equals(account)){
			account_text.setText(account);
			account_signin.setVisibility(View.GONE);
			account_signup.setVisibility(View.GONE);
			account_signout.setVisibility(View.VISIBLE);
		}else{
			account_signin.setVisibility(View.VISIBLE);
			account_signup.setVisibility(View.VISIBLE);
			account_signout.setVisibility(View.GONE);
		}
		
		account_signout.setOnClickListener(signoutListener);
		account_signin.setOnClickListener(signinListener);
		account_signup.setOnClickListener(signupListener);
		
		account_list = (ListView) findViewById(R.id.account_list);
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		map.put("profile", R.drawable.netease);
		map.put("accountType", "网易微博");
		map.put("bindAccount", "netease");
		accountListData.add(map);

		map = new HashMap<String, Object>();
		map.put("profile", R.drawable.sina);
		map.put("accountType", "新浪微博");
		map.put("bindAccount", "sina");
		accountListData.add(map);
		
		map = new HashMap<String, Object>();
		map.put("profile", R.drawable.qq);
		map.put("accountType", "腾讯微博");
		map.put("bindAccount", "qq");
		accountListData.add(map);
		
		map = new HashMap<String, Object>();
        map.put("profile", R.drawable.renren);
        map.put("accountType", "人人网");
        map.put("bindAccount", "renren");
        accountListData.add(map);
        
        map = new HashMap<String, Object>();
        map.put("profile", R.drawable.ydnote);
        map.put("accountType", "有道云笔记");
        map.put("bindAccount", "ydnote");
        accountListData.add(map);
        
    	adapter = new SimpleAdapter(this, accountListData,
    			R.layout.account_list_item,
        		new String[]{"profile", "accountType", "bindAccount"},
        		new int[]{R.id.account_img, R.id.account_type, R.id.bind_button});
    	adapter.setViewBinder((ViewBinder) new ButtonItem());
    	
    	LinearLayout footview = new LinearLayout(this);
    	foottextview = new TextView(this);
    	foottextview.setPadding(15, 5, 5, 5);
    	foottextview.setText(R.string.bind_description);
    	foottextview.setTextColor(0xff8E8E8E);
    	footview.addView(foottextview, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        account_list.addFooterView(footview);
    	account_list.setAdapter(adapter);
    	
    	progressDialog = new ProgressDialog(AccountSettingActivity.this);
    	progressDialog.setMessage("正在处理微博绑定帐号");
    	
	}
	
	/** 登录Button Listener */
	private OnClickListener signinListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			Intent Loginintent = new Intent(AccountSettingActivity.this, AccountLogin.class);
			AccountSettingActivity.this.startActivity(Loginintent);
			
		}
	};
	/** 注册Button Listener */
	private OnClickListener signupListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {

		    Intent i = new Intent(AccountSettingActivity.this, AccountWebViewRegister.class);
            startActivity(i);
			
		}
	};
	
	/** 注销Button Listener */
	private OnClickListener signoutListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			set_prefs.edit().putString("account", "").commit();
			account_text.setText(AccountSettingActivity.this.getResources().getString(R.string.no_account));
			account_signin.setVisibility(View.VISIBLE);
			account_signup.setVisibility(View.VISIBLE);
			account_signout.setVisibility(View.GONE);
		}
	};
	


	private ProgressDialog progressDialog;
	private OnClickListener bindAccountListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if (v.getTag() != null) {
			    
				String tag = v.getTag().toString();
				
				
				if(tag.contains("sina")) {
					if(tag.contains("unbind")) {		        
				        db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE+ " where " 
							     + NewsSQLiteOpenHelper.OAUTH_TYPE + "='sina'");
				        ((Button)v).setText("绑定");
				        v.setTag("sina_bind");
				        CookieSyncManager.createInstance(AccountSettingActivity.this);
                        CookieManager cookieManager = CookieManager.getInstance(); 
                        cookieManager.removeAllCookie();
					} else {
			        	Intent intent = new Intent(AccountSettingActivity.this, WeiboLogin.class);
			        	intent.putExtra("weibo_type", 0);
			        	startActivityForResult(intent,0);
					}
				} else if(tag.contains("qq")) {
					if(tag.contains("unbind")) {
				        db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE+ " where " 
							     + NewsSQLiteOpenHelper.OAUTH_TYPE + "='qq'");
				        ((Button)v).setText("绑定");
				        v.setTag("qq_bind");
				        CookieSyncManager.createInstance(AccountSettingActivity.this);
                        CookieManager cookieManager = CookieManager.getInstance(); 
                        cookieManager.removeAllCookie();
					} else {
                        Intent intent = new Intent(AccountSettingActivity.this, WeiboLogin.class);
                        intent.putExtra("weibo_type", 1);
                        startActivityForResult(intent,0);
					}
				}else if(tag.contains("netease")){
					if(tag.contains("unbind")) {		        
				        db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE+ " where " 
							     + NewsSQLiteOpenHelper.OAUTH_TYPE + "='netease'");
				        ((Button)v).setText("绑定");
				        v.setTag("netease_bind");
				        CookieSyncManager.createInstance(AccountSettingActivity.this);
                        CookieManager cookieManager = CookieManager.getInstance(); 
                        cookieManager.removeAllCookie();
					} else {
			        	Intent intent = new Intent(AccountSettingActivity.this, WeiboLogin.class);
			        	intent.putExtra("weibo_type", 2);
			        	startActivityForResult(intent,0);
					}
				}else if(tag.contains("renren")){
                    if(tag.contains("unbind")) {                
                        db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE+ " where " 
                                 + NewsSQLiteOpenHelper.OAUTH_TYPE + "='renren'");
                        ((Button)v).setText("绑定");
                        v.setTag("renren_bind");
                        CookieSyncManager.createInstance(AccountSettingActivity.this);
                        CookieManager cookieManager = CookieManager.getInstance(); 
                        cookieManager.removeAllCookie();
                    } else {
                        Intent intent = new Intent(AccountSettingActivity.this, WeiboLogin.class);
                        intent.putExtra("weibo_type", 3);
                        startActivityForResult(intent,0);
                    }
                } else if (tag.contains("ydnote")){
                	if(tag.contains("unbind")) {                
                        db.execSQL("delete from " + NewsSQLiteOpenHelper.OAUTH_TABLE+ " where " 
                                 + NewsSQLiteOpenHelper.OAUTH_TYPE + "='ydnote'");
                        ((Button)v).setText("绑定");
                        v.setTag("ydnote_bind");
                        CookieSyncManager.createInstance(AccountSettingActivity.this);
                        CookieManager cookieManager = CookieManager.getInstance(); 
                        cookieManager.removeAllCookie();
                    } else {
                        Intent intent = new Intent(AccountSettingActivity.this, WeiboLogin.class);
                        intent.putExtra("weibo_type", 4);
                        startActivityForResult(intent,0);
                    }
                }

			}
		}
	};
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == Activity.RESULT_OK){
            
            if(accountListData.size()>0){
                Tools.ChangeList(accountListData);
                adapter.setViewBinder((ViewBinder) new ButtonItem());
            }
            if(null!=adapter){
                adapter.notifyDataSetChanged();
            } 
        }
    }

	@Override
	protected void onResume() {
		
		account = set_prefs.getString("account", "");
		if(!"".equals(account)){
			account_text.setText(account);
			account_signin.setVisibility(View.GONE);
			account_signup.setVisibility(View.GONE);
			account_signout.setVisibility(View.VISIBLE);
		}else{
			account_signin.setVisibility(View.VISIBLE);
			account_signup.setVisibility(View.VISIBLE);
			account_signout.setVisibility(View.GONE);
		}
		
		super.onResume();
	}

	private class ButtonItem implements SimpleAdapter.ViewBinder {

		@Override
		public boolean setViewValue(View view, Object data,
				String key) {
			// check if the view is a button
			if (view.getId() == R.id.bind_button) {
			    getThemeSettingsHelper().setViewBackgroud(AccountSettingActivity.this, view, R.drawable.netease_small_button);
			    getThemeSettingsHelper().setTextViewColor(AccountSettingActivity.this, (TextView)view, R.color.list_title_color);
		        String sql = "";
				if(key.equals("sina")) {       
					sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
					     + NewsSQLiteOpenHelper.OAUTH_TYPE + "=?";

			        Cursor cursor = db.rawQuery(sql, new String[]{"sina"});
			        if(cursor != null && cursor.getCount()!= 0 ) { 
			        	((Button)view).setText("取消绑定");
			        	view.setTag("sina_unbind");
			        } else {
			        	((Button)view).setText("绑定");
			        	view.setTag("sina_bind");
			        }
			        if(cursor != null) cursor.close();
					
				} else if(key.equals("qq")) {
					sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
				     + NewsSQLiteOpenHelper.OAUTH_TYPE + "=?";

		            Cursor cursor = db.rawQuery(sql, new String[]{"qq"});
		            if(cursor != null && cursor.getCount()!= 0 ) { 
		        	    ((Button)view).setText("取消绑定");
		        	    view.setTag("qq_unbind");
		            } else {
		        	    ((Button)view).setText("绑定");
		        	    view.setTag("qq_bind");
		            }
		            if(cursor != null) cursor.close();				  
				} else if(key.equals("netease")){
					sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
				     + NewsSQLiteOpenHelper.OAUTH_TYPE + "=?";

		            Cursor cursor = db.rawQuery(sql, new String[]{"netease"});
		            if(cursor != null && cursor.getCount()!= 0 ) { 
		        	    ((Button)view).setText("取消绑定");
		        	    view.setTag("netease_unbind");
		            } else {
		        	    ((Button)view).setText("绑定");
		        	    view.setTag("netease_bind");
		            }
		            if(cursor != null) cursor.close();		
				}else if(key.equals("renren")){
                    sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
                    + NewsSQLiteOpenHelper.OAUTH_TYPE + "=?";

                   Cursor cursor = db.rawQuery(sql, new String[]{"renren"});
                   if(cursor != null && cursor.getCount()!= 0 ) { 
                       ((Button)view).setText("取消绑定");
                       view.setTag("renren_unbind");
                   } else {
                       ((Button)view).setText("绑定");
                       view.setTag("renren_bind");
                   }
                   if(cursor != null) cursor.close();      
               } else if(key.equals("ydnote")){
            	   sql = "select * from " + NewsSQLiteOpenHelper.OAUTH_TABLE + " where " 
                   + NewsSQLiteOpenHelper.OAUTH_TYPE + "=?";

                  Cursor cursor = db.rawQuery(sql, new String[]{"ydnote"});
                  if(cursor != null && cursor.getCount()!= 0 ) { 
                      ((Button)view).setText("取消绑定");
                      view.setTag("ydnote_unbind");
                  } else {
                      ((Button)view).setText("绑定");
                      view.setTag("ydnote_bind");
                  }
                  if(cursor != null) cursor.close();     
               }
				
				view.setOnClickListener(bindAccountListener);	
			
				return true;
			} else if (view.getId() == R.id.account_type) {
			    getThemeSettingsHelper().setTextViewColor(AccountSettingActivity.this, (TextView)view, R.color.list_title_color);
			}
			return false;
		}

	}

	public void goBackClick(View view){
		finish();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if(progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss();
	}

    @Override
    public void onApplyTheme() {
        super.onApplyTheme();
        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        themeSettingsHelper.setTextViewColor(this, R.id.top_main_text, R.color.main_title_color);
        themeSettingsHelper.setViewBackgroud(this, R.id.top_main_bottom, R.drawable.top_background);
        themeSettingsHelper.setViewBackgroudColor(this, R.id.account_setting_main, R.color.main_bg_color);
        themeSettingsHelper.setTextViewColor(this, R.id.account_signout, R.color.list_title_color);
        themeSettingsHelper.setViewBackgroud(this, R.id.account_signout, R.drawable.netease_small_button);
        themeSettingsHelper.setTextViewColor(this, R.id.account_signup, R.color.list_title_color);
        themeSettingsHelper.setViewBackgroud(this, R.id.account_signup, R.drawable.netease_small_button);
        themeSettingsHelper.setTextViewColor(this, R.id.account_signin, R.color.list_title_color);
        themeSettingsHelper.setViewBackgroud(this, R.id.account_signin, R.drawable.netease_small_button);
        themeSettingsHelper.setListViewDivider(this, R.id.account_list, R.drawable.list_divider_line);
        themeSettingsHelper.setTextViewColor(this, R.id.title_netease, R.color.main_title_color);
        themeSettingsHelper.setTextViewColor(this, R.id.title_other_platform, R.color.main_title_color);
        themeSettingsHelper.setTextViewColor(this, R.id.account_text, R.color.list_title_color);
      //返回夜间模式
        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_common_btn, R.drawable.go_back);
    }
	
	
	
}
